<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport"
        content="width=device-width, initial-scale=1.0,minimum-scale=1,maximum-scale=1,user-scalable=no" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <!-- <link rel="stylesheet" type="text/css" href="css/index.css">
    <script type="text/javascript" src="js/index.js"></script>
    <style type="text/css"></style> -->
    <title>Document</title>
    <style>
        table {
            margin: 20px auto;
            text-align: center;
            width: 500px;
        }

        form {
            width: 500px;
            margin: 0 auto;
        }

        table tbody tr td:nth-child(1) {
            text-align: left;
        }

        table thead tr th:nth-child(1) {
            text-align: left;
        }
    </style>
</head>

<body>
    <form>
        商品名称：<input type="text" class="name" /><br />
        单价：<input type="text" class="price" /><br />
        数量：<input type="text" class="number" /><br />
        <input type="button" value="添加" class="add" />
    </form>
    <!-- <button class="add">添加</button> -->
    <table border="1" cellspacing="0">
        <thead>
            <tr>
                <th><input id="check" type="checkbox"><label for="check">全选</label></th>
                <th>编号</th>
                <th>商品名称</th>
                <th>单价</th>
                <th>数量</th>
                <th>小计</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
            <!-- <tr>
                <td>1</td>
                <td>小米</td>
                <td>2999</td>
                <td>
                    <button>-</button>
                    <input type="text" value="1" style="width:20px" />
                    <button>+</button>
                </td>
                <td>2999</td>
                <td>
                    <button class="remove">删除</button>
                </td>
            </tr> -->
        </tbody>
        <tfoot>
            <tr>
                <td colspan="5">总计</td>
                <td colspan="2" class="allTotal-box">0</td>
            </tr>
        </tfoot>
    </table>

    <script>
        //商品对象数组
        const gods = [{
                id: 1,
                name: "小米手机",
                price: 2999,
                number: 1,
            },
            {
                id: 2,
                name: "华为手机",
                price: 3999,
                number: 1,
            },
            {
                id: 3,
                name: "iphone",
                price: 5999,
                number: 1,
            },
            {
                id: 4,
                name: "vivo手机",
                price: 1999,
                number: 1,
            },
        ];
        //获取页面元素
        const tbody = document.querySelector("tbody");
        const addBtn = document.querySelector(".add");
        const nameInp = document.querySelector(".name");
        const numberInp = document.querySelector(".number");
        const priceInp = document.querySelector(".price");
        //执行渲染表格
        bindHtml();
        //渲染表格函数
        function bindHtml() {
            let str = "";
            gods.forEach(function (item) {
                str += `
            <tr>
                <td><input type="checkbox" class="check-items"></td>
                <td>${item.id}</td>
                <td>${item.name}</td>
                <td>${item.price}</td>
                <td>
                    <button class="down">-</button>
                    <input type="text" class="_inp" value="${item.number}" style="width:20px"/>
                    <button class="up">+</button>
                </td>
                <td class="total">${item.price * item.number}</td>
                <td>
                    <button class="remove">删除</button>
                </td>
            </tr>
            `;
            });
            tbody.innerHTML = str;
        }
        /* **************************添加商品********************************  */
        //添加函数
        addBtn.onclick = function () {
            const name = nameInp.value.trim();
            const price = priceInp.value.trim();
            const number = numberInp.value.trim();

            if (name === "" || price === "" || number === "") {
                return alert("请完整填写表单！");
            }
            const god = {
                id: 0,
                name: name,
                price: price,
                number: number,
            };
            if (gods.length) {
                god.id = gods[gods.length - 1].id + 1;
            } else {
                god.id = 1;
            }
            /* **************************判断加入地商品是否重复********************************  */
            let res= gods.find(function(curr){
                return god.name===curr.name&&god.price===gods.price
            })
            if(res!==undefined){//如果重复则把添加的商品的数量加到重复的数量上
                res.number+=Number(god.number)
            }else{//不重复则把添加的数据插入到数组中
                gods.push(god)
            }
            bindHtml();//重新渲染添加成功后的数组
            /* 将添加框里的内容置空 */
            nameInp.value = "";
            priceInp.value = "";
            numberInp.value = "";
            /* 给新添加的商品加上删除、数量加、数量减、总计和手动输入数量的功能 */
            remove()
            up()
            down()
            sumTotal()
            input()
            /* 添加成功后将全选按钮设置为未选中 */
            let allChecked = document.querySelector('#check')
            allChecked.checked = false

        };
        //console.log(gods);
        /* **************************删除商品********************************  */
        //删除按钮
        function remove() {
            let removes = document.querySelectorAll('.remove')
            for (let i = 0; i < removes.length; i++) {
                removes[i].onclick = function (e) {
                    const _tr = e.target.parentNode.parentNode
                    gods.splice(i, 1)
                    _tr.remove()
                    sumTotal()
                }
            }
        }
        remove()
        /* **************************数量加********************************  */
        function up() {
            //数量加
            let upBtns = document.querySelectorAll('.up')
            //let number=document.querySelectorAll('tbody input[typr="text"]')
            //console.log(upBtns);
            for (let i = 0; i < upBtns.length; i++) {
                upBtns[i].onclick = function (e) {
                    let numInput = e.target.previousElementSibling
                    //console.log(numInput);
                    numInput.value = Number(numInput.value) + 1
                    let price = e.target.parentNode.previousElementSibling
                    // console.log(price.innerText);
                    let currTotal = e.target.parentNode.nextElementSibling
                    //console.log(currTotal);
                    currTotal.innerText = Number(price.innerText) * numInput.value
                    sumTotal()
                }
            }
        }
        up()

        /* **************************数量减********************************  */
        function down() {
            let downBtns = document.querySelectorAll('.down')
            for (let i = 0; i < downBtns.length; i++) {
                downBtns[i].onclick = function (e) {
                    let numInput = e.target.nextElementSibling
                    //console.log(numInput);
                    if (numInput.value <= 0) {
                        return
                    } else {
                        numInput.value = Number(numInput.value) - 1
                        let price = e.target.parentNode.previousElementSibling
                        //console.log(price.innerText);
                        let currTotal = e.target.parentNode.nextElementSibling
                        //console.log(currTotal);
                        currTotal.innerText = Number(price.innerText) * numInput.value
                        sumTotal()
                    }

                }
            }
        }
        down()
        /* **************************手动输入数量********************************  */
        function input() {
            let inputList = document.querySelectorAll('._inp')
            //console.log(inputList);
            for (let i = 0; i < inputList.length; i++) {
                inputList[i].oninput = function (e) {
                    //console.log(e.target);
                    //console.log(e.target.value);
                    let currTotal = e.target.parentNode.nextElementSibling
                    let price = e.target.parentNode.previousElementSibling
                    if (e.target.value.trim() === '') {
                        e.target.value = 0
                    }
                    currTotal.innerText = Number(price.innerText) * Number(e.target.value)
                    sumTotal()
                }
            }
        }
        input()
        /* **************************复选框********************************  */
        function allCheckFunction() {
            //全选操作
            let allChecked = document.querySelector('#check')
            allChecked.onchange = function (e) {
                e = e || window.event
                const _check = e.target.checked
                //console.log(_check);
                const checkItemsList = document.querySelectorAll('.check-items')
                //console.log(checkItemsList);
                checkItemsList.forEach(function (items) {
                    items.checked = _check
                })
                sumTotal()
            }
        }
        allCheckFunction()
        //单选操作
        function singleCheckFunction() {
            let cartBody = document.querySelector('tbody')
            //console.log(cartBody);
            cartBody.addEventListener('change', function (e) {
                if (e.target.classList.contains('check-items')) {
                    const checkItemsList = document.querySelectorAll('.check-items')
                    //console.log(checkItemsList);
                    const _checked = Array.from(checkItemsList).every(function (curr) {
                        return curr.checked
                    })
                    const allChecked = document.querySelector('#check')
                    //console.log(allChecked);
                    allChecked.checked = _checked
                    sumTotal()
                }
                //console.log(_checked);
            }, false)
        }
        singleCheckFunction()

        /* **************************计算所有总价********************************  */
        function sumTotal() {
            //let total = document.querySelectorAll('.total')
            let checkedItemsList = document.querySelectorAll('.check-items:checked')
            let allTotalBox = document.querySelector('.allTotal-box')
            //console.log(allTotalBox);
            //console.log(total);
            let allTotal = 0
            checkedItemsList.forEach(function (items) {

                allTotal += Number(items.parentNode.parentNode.children[5].innerText)
                //console.log(items.innerText);
            })
            allTotalBox.innerText = allTotal
        }
        sumTotal()
    </script>
</body>

</html>